package yxy.game.pm2.command.tower;

import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.tower;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Format;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.TowerMessage;
import yxy.game.pm2.module.hero.FormatHandle;
import yxy.game.pm2.module.tower.TowerHandle;
import yxy.game.pm2.module.tower.TowerModule;

/** 修炼塔 挑战 */
@MessageType(proto = Command.TowerChanllenge, classtype = TowerMessage.TowerChanllengeRequest.class)
public class CMD_TowerChanllenge extends Command<TowerMessage.TowerChanllengeRequest> {

	@Override
	public void execute(MessageSource messageSource, TowerMessage.TowerChanllengeRequest request) {
		String playerCode = messageSource.getTag();
		int floor = request.getFloor();

		TowerMessage.TowerChanllengeResponse.Builder response = TowerMessage.TowerChanllengeResponse.newBuilder();

		TowerHandle handle = new TowerHandle();
		if (handle.isBattling(playerCode)) {
			send(messageSource, response, Result.BattleIsRunning);// 之前的战斗未结束
			return;
		}

		FormatHandle formatHandle = new FormatHandle();
		Result result = formatHandle.check(playerCode, formatHandle.get(playerCode, Format.FormatType.普通));
		if (!result.equals(Result.Success)) {
			send(messageSource, response, result);   //  重复武将判断
			return;
		}

		// 判断次数
		TowerModule towerModule = TowerModule.get(playerCode);
		if (floor <= towerModule.getFloor() && towerModule.remainTimes() <= 0) {
			send(messageSource, response, Result.TowerChanllengeTimesLack);// 没有挑战次数了
			return;
		}
		if (floor > towerModule.getFloor() + 1) {
			send(messageSource, response, Result.TowerChanllengeFloor);// 你还不能挑战这层
			return;
		}
		tower data = DataCenter.getData(floor, tower.class);
		if (data == null) {
			send(messageSource, response, Result.ParamError);
			return;
		}

		try {
			response.setBattle(handle.battleResponse(playerCode, floor, floor > towerModule.getFloor()));
			send(messageSource, response, Result.Success);
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		}

	}

	private void send(MessageSource messageSource, TowerMessage.TowerChanllengeResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}